package com.smartlink.app.activity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.smartlink.app.R;
import com.smartlink.app.util.NetWorkUtil;

public class SetIpActivity extends Activity implements View.OnClickListener {

    private EditText et_setip_ip;
    private Button btn_setip_save;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_ip);
        et_setip_ip = (EditText) findViewById(R.id.et_setip_ip);
        btn_setip_save = (Button) findViewById(R.id.btn_setip_save);
        sharedPreferences = getSharedPreferences("main", MODE_PRIVATE);
        btn_setip_save.setOnClickListener(this);
    }

    /**
     * 检查并保存IP
     */
    private void setIp() {
        if (!TextUtils.isEmpty(et_setip_ip.getText())) {
            String ip = et_setip_ip.getText().toString();
            String regular = "((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))";
            if (ip.matches(regular)) {
                boolean flag = NetWorkUtil.pingIP(ip);
                if (flag) {
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("ip", ip);
                    editor.apply();
                    Toast.makeText(this, "设置成功", Toast.LENGTH_SHORT).show();
                    finish();

                } else {
                    Toast.makeText(this, "代理Ip错误，请重新设置", Toast.LENGTH_SHORT).show();
                }

            } else {
                Toast.makeText(this, "请输入正确的ip地址", Toast.LENGTH_SHORT).show();
            }

        } else {
            Toast.makeText(this, "代理Ip不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        setIp();
    }
}
